package com.iflytek.springboot_medicine.service.impl;

import com.iflytek.springboot_medicine.entity.Medicine;
import com.iflytek.springboot_medicine.pojo.MedicinePojo;
import com.iflytek.springboot_medicine.service.CategoryRepository;
import com.iflytek.springboot_medicine.service.MedicineRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MedicineServiceImpl {
    private final MedicineRepository medicineRespository;
    private final CategoryRepository categoryRespository;

    public MedicineServiceImpl(MedicineRepository medicineRespository, CategoryRepository categoryRespository) {
        this.medicineRespository = medicineRespository;
        this.categoryRespository = categoryRespository;
    }

    /**
     * 将 Page<Medicine> 转换为 Page<MedicinePojo>
     * @param name
     * @param category
     * @param pageable
     * @return
     */
    public Page<MedicinePojo> getMedicinesByCriteriaAsDTO(String name, String category, Pageable pageable) {
        Page<Medicine> medicines = medicineRespository.findByMedicineNameAndCategoryName(name, category, pageable);
        return medicines.map(MedicinePojo::new);
    }

    /**
     * 删除药材
     * @param id
     * @return
     */
    public Medicine deleteMedicineById(int id) {
        return medicineRespository.deleteById(id);
    }

    /**
     * 批量删除药材
     */
    public void deleteAllInBatch(List<Integer> ids) {
        medicineRespository.deleteAllByIdInBatch(ids);
    }

    /**
     * 根据类别查找ID
     * @param name
     * @return
     */
    public int selectByName(String name) {
        int byName = categoryRespository.findIdByName(name);
        System.out.println(byName+"~~~~~~~~~~~~");
        return byName;
    }

    /**
     * 存储更新的Medicine
     * @param medicine
     * @return
     */
    public Medicine saveMedicine(Medicine medicine) {
        return medicineRespository.save(medicine);
    }

    /**
     * 分页查询
     * @param pageNum
     * @param pageSize
     * @return
     */
    public Pageable findCategory(int pageNum, int pageSize) {
        // 构建分页请求
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
        // 执行分页查询
        return pageable;
    }

    /**
     * 添加药材
     * @param medicine
     * @return
     */
    public Medicine addMedicine(Medicine medicine) {
        return medicineRespository.save(medicine);
    }

    public Medicine findMedicineByName(String name) {
        return medicineRespository.findByName(name);
    }

    public List<Medicine> findAllMedicine() {
        return medicineRespository.findAll();
    }

}
